<?php


namespace api\blog\controller;


use api\blog\validate\UserValidate;
use cmf\controller\RestBaseController;
use api\blog\model\UserModel;

class UserController extends RestBaseController
{
    //验证码
    public function sendCode(){
        $mobile = input('mobile');
        //验证验证码
        $code = sendAliSms($mobile);
        if($code['code'] == 1){
            $this->success('发送成功');
        }else{
            $this->error($code['msg']);
        }
    }
    //注册
    public function register(){
        //接收数据
        $data = input('post.');
        //查重
        $mobile = UserModel::where('mobile',$data['mobile'])->find();
        if($mobile){
            $this->error('账号已存在');
        }
        //验证
        $validate = new UserValidate();
        $result = $validate->scene('register')->check($data);
        //判断
        if(!$result){
            $this->error($validate->getError());
        }
        //验证验证码是否存在
        // $code = Db::name('sms_code_log')->where('mobile',$data['mobile'])->find();
        $check = checkSmsCode($data['mobile'],$data['code']);
        if(!$check){
            $this->error('验证码错误');
        }
//        //密码
//        $randStr = createRandStr(8);
//        $data['password'] = md5($data['password'].$randStr);
//        $data['salt'] = $randStr;
        $user = UserModel::create([
            'mobile' => $data['mobile']
        ]);

        //入库
        if($user){
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }
    }
    //登录
    public function login(){
        //接收
        $data = input('post.');
        //验证
        $validate = new UserValidate();
        $result = $validate->scene('login')->check($data);
        //判断
        if(!$result){
            $this->error($validate->getError());
        }
        //查询账号
        $user = UserModel::where('mobile',$data['mobile'])->find();
        //验证验证码是否存在
        $check = checkSmsCode($data['mobile'],$data['code']);
        if($check){
                $token = signToken($data['id'],$data['mobile']);
                $this->success(
                    '登录成功',
                    [
                        'data'=>$token
                    ]
                );
        }else{
            $this->error('验证码错误');
        }
        if(!$user){
            $this->error('该账号不存在');
        }
        $this->success('登录成功');
    }
}